package com.hello.booksale.service;

import com.alibaba.fastjson2.JSON;
import com.hello.booksale.configuration.QiniuProperties;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;

@Slf4j
@Service
public class QiniuService {
    @Resource
    private QiniuProperties qiniuProperties;

    @Resource
    private UploadManager uploadManager;

    @Resource
    private BucketManager bucketManager;
    @Resource
    private Auth auth;


    public String uploadFile(InputStream inputStream) throws QiniuException {
        Response response = uploadManager.put(inputStream, null, getUploadToken(), null, null);
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = uploadManager.put(inputStream, null, getUploadToken(), null, null);
            retry++;
        }
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        String imgUrl = qiniuProperties.getPrefix() + "/" + putRet.key;
        return imgUrl;
    }

    public Response delete(String key) throws QiniuException {
        Response response = bucketManager.delete(qiniuProperties.getBucket(), key);
        int retry = 0;
        while (response.needRetry() && retry++ < 3) {
            response = bucketManager.delete(qiniuProperties.getBucket(), key);
        }
        return response;
    }


    private String getUploadToken() {
        return auth.uploadToken(qiniuProperties.getBucket());
    }

}
